package com.wjyf.reducing_bento.interceptor;


import com.wjyf.reducing_bento.common.ErrorCode;
import com.wjyf.reducing_bento.exception.BusinessException;
import com.wjyf.reducing_bento.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.wjyf.reducing_bento.constant.UserConstant.USER_SESSION_KEY;

/**
 * @Author: lrk
 * @Date: 2022/11/21 上午 10:56
 * @Description:
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("******进入拦截器********");
        //axios在发送请求之前需要先发送一个OPTIONS预请求，相当于请求两次，直接放行
        //if ("OPTIONS".equals(request.getMethod())) {
        //    //true是直接放行，前端抓包会有options请求
        //    return true;
        //    //false拒接访问，抓包就不会有options请求了
        //}
        log.info(request.getServletPath());
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        try {
            JwtUtils.parseJWT(token);
        }catch (Exception e){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "非法token");
        }
        // 解决跨域
        //response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        //response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, GET");
        //response.setHeader("Access-Control-Max-Age", "3600");
        //response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        //response.setHeader("Access-Control-Allow-Credentials", "true");
        return true;
    }


}
